import { Region } from '@/app/types/region'
import React, { useState } from 'react'

interface RegionTableProps {
  regions: Region[]
  onEdit: (region: Region) => void
  onDelete: (id: string) => void
  onAddSub: (parentCode: string) => void
  onLoadChildren: (parentCode: string) => Promise<Region[]>
}

export default function RegionTable({ regions, onEdit, onDelete, onAddSub, onLoadChildren }: RegionTableProps) {
  const [expandedNodes, setExpandedNodes] = useState<Set<string>>(new Set())
  const [childrenMap, setChildrenMap] = useState<Record<string, Region[]>>({})
  const [loadingNodes, setLoadingNodes] = useState<Set<string>>(new Set())

  const getLevelName = (level: number) => {
    const levels = ['省', '市', '区县', '街镇', '村居']
    return levels[level - 1]
  }

  const handleToggleNode = async (region: Region) => {
    // 如果已经展开，则直接收起
    if (expandedNodes.has(region.code)) {
      const newExpanded = new Set(expandedNodes);
      newExpanded.delete(region.code);
      setExpandedNodes(newExpanded);
      return;
    }

    // 如果正在加载中，直接返回
    if (loadingNodes.has(region.code)) {
      return;
    }

    try {
      // 设置加载状态
      setLoadingNodes(prev => new Set([...prev, region.code]));

      // 如果已经有缓存的子节点数据，直接使用
      if (childrenMap[region.code]) {
        setExpandedNodes(prev => new Set([...prev, region.code]));
        return;
      }

      // 加载子节点数据
      const response = await onLoadChildren(region.code);
      if (!response) return;

      // 更新子节点数据
      setChildrenMap(prev => ({
        ...prev,
        [region.code]: response
      }));

      // 展开节点
      setExpandedNodes(prev => new Set([...prev, region.code]));

    } catch (error) {
      console.error('加载子节点失败:', error);
    } finally {
      // 清除加载状态
      setLoadingNodes(prev => {
        const newSet = new Set(prev);
        newSet.delete(region.code);
        return newSet;
      });
    }
  };

  const renderTableRows = () => {
    const rows: JSX.Element[] = [];
    const stack: { node: Region; level: number }[] = regions
      .filter(region => region.level === 1)
      .map(node => ({ node, level: 0 }));

    while (stack.length > 0) {
      const { node: region, level } = stack.pop()!;
      const isExpanded = expandedNodes.has(region.code);
      const hasChildren = childrenMap[region.code]?.length > 0;

      rows.push(
        <tr key={region.id}>
          <td className="px-6 py-4 text-white/90">
            <div className="flex items-center">
              <span style={{ marginLeft: `${level * 20}px` }} className="flex items-center">
                {region.level < 5 && (
                  <button 
                    onClick={() => handleToggleNode(region)}
                    className="mr-2 w-4 h-4 flex items-center justify-center"
                  >
                    {loadingNodes.has(region.code) ? (
                      <span className="animate-spin">↻</span>
                    ) : (
                      isExpanded ? '▼' : '▶'
                    )}
                  </button>
                )}
                {region.name}
              </span>
            </div>
          </td>
          <td className="px-6 py-4 text-white/90">{region.code}</td>
          <td className="px-6 py-4 text-white/90">{getLevelName(region.level)}</td>
          <td className="px-6 py-4 text-white/90">{region.orderNum}</td>
          <td className="px-6 py-4 text-white/90">{region.status ? '启用' : '停用'}</td>
          <td className="px-6 py-4 space-x-2">
            <button onClick={() => onEdit(region)} className="text-blue-300 hover:text-blue-100">
              编辑
            </button>
            {region.level < 5 && (
              <button onClick={() => onAddSub(region.code)} className="text-green-300 hover:text-green-100">
                添加下级
              </button>
            )}
            <button onClick={() => onDelete(region.id)} className="text-rose-300 hover:text-rose-100">
              删除
            </button>
          </td>
        </tr>
      );

      // 如果节点展开且有子节点，将子节点添加到栈中
      if (isExpanded && hasChildren) {
        // 反转数组以保持正确的显示顺序
        const children = [...childrenMap[region.code]].reverse();
        children.forEach(child => {
          stack.push({ node: child, level: level + 1 });
        });
      }
    }

    return rows;
  };

  return (
    <div className="overflow-x-auto">
      <table className="min-w-full divide-y divide-gray-200/20">
        <thead>
          <tr>
            <th className="px-6 py-3 text-left text-white">名称</th>
            <th className="px-6 py-3 text-left text-white">区划代码</th>
            <th className="px-6 py-3 text-left text-white">级别</th>
            <th className="px-6 py-3 text-left text-white">排序</th>
            <th className="px-6 py-3 text-left text-white">状态</th>
            <th className="px-6 py-3 text-left text-white">操作</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-gray-200/20">
          {renderTableRows()}
        </tbody>
      </table>
    </div>
  )
} 